package com.gable.exhibition.log;

import com.alibaba.fastjson.JSON;
import com.gable.common.util.CacheData;
import com.gable.common.util.UUIDGenerator;
import com.gable.exhibition.dao.LogDao;
import com.gable.exhibition.model.Log;
import com.gable.exhibition.model.User;
import com.google.common.collect.Maps;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map;

/**
 * Created by Lesson on 2018/3/2.
 */
//@Component
//@Aspect
public class LogAop {

        Logger logger = Logger.getLogger(this.getClass());

        @Autowired
        LogDao logDao;

        @Pointcut("execution(* com.gable.exhibition.dao..*.*(..))" )
        public void executeService(){
                logger.info("进入环绕通知");
        }

        @Before("executeService()")
        public void doBeforeAdvice(JoinPoint joinPoint){
            logger.debug("开始记录日志");
            //获取目标方法的参数信息
            Object[] obj = joinPoint.getArgs();
            //AOP代理类的信息
            joinPoint.getThis();
            //代理的目标对象
            joinPoint.getTarget();
            //用的最多 通知的签名
            Signature signature = joinPoint.getSignature();
            //代理的是哪一个方法
            System.out.println(signature.getName());
            //AOP代理类的名字
            System.out.println(signature.getDeclaringTypeName());
            //AOP代理类的类（class）信息
            signature.getDeclaringType();
            //获取RequestAttributes
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            //从获取RequestAttributes中获取HttpServletRequest的信息
            HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
            //如果要获取Session信息的话，可以这样写：
            //HttpSession session = (HttpSession) requestAttributes.resolveReference(RequestAttributes.REFERENCE_SESSION);
            if(signature.getName().toLowerCase().indexOf("init")>-1 || signature.getName().indexOf("queryUpkeepInfo")>-1)
                return;
            Enumeration<String> enumeration = request.getParameterNames();
            Map<String,String> parameterMap = Maps.newHashMap();
            while (enumeration.hasMoreElements()){
                String parameter = enumeration.nextElement();
                parameterMap.put(parameter,request.getParameter(parameter));
            }
            String parameterStr = JSON.toJSONString(parameterMap);
            if(obj.length > 0) {
                System.out.println("请求的参数信息为："+parameterStr);
            }
            try{

                User user = CacheData.getSessionUser(null,1);
                if(user == null){
                    return;
                }
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Log log = new Log();
                log.setLogId(UUIDGenerator.getUniqueLong());
                log.setFuntionName(signature.getName());
                log.setOperationPerson(user.getUserId());
                log.setOperationTime(df.format(new Date()));
                log.setClassName(signature.getDeclaringTypeName());
                log.setParameter(parameterStr);
                request.setAttribute("log", log);
               /* InterfaceLog il = new InterfaceLog();
                il.setId(UUIDGenerator.getMilesLong());
                il.setFuntionName(signature.getName());
                il.setUrl(request.getRequestURL().toString());
                il.setParameter(parameterStr);
                il.setRequestTime(sdf.format(new Date()));
                interfaceLogService.addInterfaceLog(il);
                request.setAttribute("logId", il.getId());*/
            }catch (Exception e) {
                e.printStackTrace();
            }

        }



           @AfterReturning(value="execution(* com.gable.exhibition.dao..*.*(..))",returning="result")
    public void afterReturning(JoinPoint joinPoint, int result){
        User user  = CacheData.getSessionUser(null,1);
        if(user == null){
            return;
        }
               RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
               //从获取RequestAttributes中获取HttpServletRequest的信息
               HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        String methodName = joinPoint.getSignature().getName();
        if(methodName.indexOf("insert") > -1 || methodName.indexOf("update") > -1 || methodName.indexOf("delete") > -1){
            logger.info("记录日志");
            Log log = (Log)request.getAttribute("log");
            if(result > 0){
                log.setReturnResult("操作成功");
            }else{
                log.setReturnResult("操作失败");
            }
            log.setComment("操作正常");
            logDao.add(log);
        }
        logger.info("环绕通知结束");
    }

    @AfterThrowing(value = "executeService()",throwing = "exception")
    public void doAfterThrowingAdvice(JoinPoint joinPoint,Throwable exception){
        //获取RequestAttributes
     /*   RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        Long id = Long.parseLong(request.getAttribute("logId").toString());*/
        /*InterfaceLog il = new InterfaceLog();
        il.setId(id);
        il.setComment("程序执行出现异常");
        interfaceLogService.updateInterfaceLog(il);*/
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        String methodName = joinPoint.getSignature().getName();
        if(methodName.toLowerCase().indexOf("init")>-1 || methodName.indexOf("queryUpkeepInfo")>-1)
            return;

        if(request.getAttribute("log") != null){
            Log log = (Log)request.getAttribute("log");
            if(log == null){
                return;
            }
            log.setComment("程序执行出现异常");
            logDao.add(log);
        }
    }
}
